<template>
  <div class="readers-container">
    <!-- 搜索操作 -->
    <el-card class="search-card">
      <div class="search-form">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="学生姓名">
            <el-input v-model="searchForm.real_name" placeholder="请输入姓名" clearable />
          </el-form-item>
          <el-form-item label="借阅卡号">
            <el-input v-model="searchForm.cardno" placeholder="借阅卡号" clearable>
              <template #append>
                <el-button :icon="Camera" @click="openScan" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="success" @click="showAddDialog"
              >添加学生</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <!-- 读者列表 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="table-card">
          <el-table :data="pagerTableData" style="width: 100%">
            <el-table-column prop="user_id" label="ID" width="60" />
            <el-table-column prop="studentno" label="学号" width="150" />
            <el-table-column prop="real_name" label="姓名" width="150" />
            <el-table-column
              prop="college_name"
              label="学院"
              width="260"
              show-overflow-tooltip
            />
            <el-table-column prop="classes" label="班级" width="150" />
            <el-table-column prop="cardno" label="借阅卡号" width="150" />
            <el-table-column prop="borrow_status" label="借阅状态" width="120">
              <template #default="scope">
                <el-tag :type="
                  scope.row.borrow_status === 0 ? 'success' : 
                  scope.row.borrow_status === 1 ? 'warning' : 'danger'
                ">
                  {{ 
                    scope.row.borrow_status === 0 ? '正常' : 
                    scope.row.borrow_status === 1 ? '已借阅' : '已逾期' 
                  }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="180">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="handleGenerateQR(scope.row)"
                  >生成借阅证</el-button
                >
                <el-button link type="success" @click="showBorrowHistory(scope.row)">借阅历史</el-button>
                <el-button link type="danger">禁用</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              :current-page="searchForm.currentPage"
              :page-size="searchForm.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              :page-count="pageTotal"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 借阅证预览弹窗 -->
    <el-dialog
      v-model="cardPreviewVisible"
      title="借阅证预览"
      width="800px"
      class="card-preview-dialog"
    >
      <div class="library-card">
        <div class="card-header">
          <h2>图书馆借阅证</h2>
          <span class="card-no"
            >No.{{ selectedReader?.cardNo || selectedReader?.cardno || "XXXXX" }}</span
          >
        </div>
        <div class="card-body">
          <!-- 左侧照片区域 -->
          <div class="card-section photo-section">
            <div class="photo-placeholder">
              <template v-if="selectedReader?.student_img">
                <img :src="selectedReader.student_img" class="student-photo" />
              </template>
              <template v-else>
                <el-icon size="40"><Avatar /></el-icon>
              </template>
            </div>
          </div>

          <!-- 中间信息区域 -->
          <div class="card-section info-section">
            <div class="info-row">
              <span class="info-label">姓名：</span>
              <span class="info-value">{{ selectedReader?.real_name }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">学号：</span>
              <span class="info-value">{{ selectedReader?.studentno }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">入学年份：</span>
              <span class="info-value">{{ selectedReader?.yearofadmission }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">学院：</span>
              <span class="info-value">{{ selectedReader?.college_name }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">专业：</span>
              <span class="info-value">{{ selectedReader?.professional }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">班级：</span>
              <span class="info-value">{{ selectedReader?.classes }}</span>
            </div>
          </div>

          <!-- 右侧二维码区域 -->
          <div class="card-section qr-section">
            <div class="qr-placeholder">
              <Qrcode :qr-url-str="selectedReader?.cardno || ''" />
            </div>
            <p class="qr-tip">扫码借阅</p>
          </div>
        </div>
        <div class="card-footer">
          <p>有效期：{{ selectedReader?.card_available }}</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cardPreviewVisible = false">关闭</el-button>
          <el-button type="primary" @click="handlePrint">打印借阅证</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加学生信息 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加学生"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form
        :model="readerForm"
        :rules="rules"
        ref="readerFormRef"
        label-width="100px"
        class="reader-form"
      >
        <!-- 添加照片上传部分 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="证件照片" prop="photo">
              <div class="upload-container">
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  :show-file-list="false"
                  :before-upload="beforePhotoUpload"
                  :http-request="handlePhotoUpload"
                >
                  <img v-if="readerForm.student_img" :src="readerForm.student_img" class="avatar" />
                  <div v-else class="avatar-placeholder">
                    <el-icon><Plus /></el-icon>
                    <span>上传照片</span>
                  </div>
                </el-upload>
                <div class="upload-tip">
                  <p>请上传证件照片，要求：</p>
                  <p>1. 图片格式：JPG、PNG</p>
                  <p>2. 图片大小：不超过2MB</p>
                  <p>3. 比例：3:4 建议尺寸：300x400px</p>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学号" prop="studentno">
              <el-input
                v-model="readerForm.studentno"
                placeholder="请输入学号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账号" prop="username">
              <el-input
                v-model="readerForm.username"
                placeholder="请输入账号名称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入学年份" prop="Yearofadmission">
              <el-date-picker
                v-model="readerForm.Yearofadmission"
                type="year"
                placeholder="请选择入学年份"
                format="YYYY"
                value-format="YYYY"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学院" prop="college_name">
              <el-cascader
                v-model="readerForm.collegeAndMajor"
                :options="collegeOptions"
                :props="{
                  value: 'value',
                  label: 'label',
                  children: 'children',
                }"
                @change="handleCollegeChange"
                placeholder="请选择学院和专业方向"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班级" prop="class">
              <el-input v-model="readerForm.class" placeholder="请输入班级" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="real_name">
              <el-input
                v-model="readerForm.real_name"
                placeholder="请输入真实姓名"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">借阅证信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="证件号" prop="cardNo">
              <el-input
                v-model="readerForm.cardNo"
                placeholder="系统自动生成"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效期" prop="card_available">
              <el-input
                v-model="readerForm.card_available"
                placeholder="系统自动生成"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddReader">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加扫码对话框 -->
    <el-dialog v-model="scanVisible" title="扫描二维码/条码" width="500px">
      <SteamBarcodeReader @decode="handleScanResult" />
    </el-dialog>

    <!-- 添加借阅历史抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="`${currentReader.real_name}的借阅历史`"
      direction="rtl"
      size="60%"
    >
      <div class="borrow-history-container">
        <!-- 统计信息卡片 -->
        <el-card class="statistics-card">
          <div class="statistics-grid">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.totalBorrow || 0 }}</div>
              <div class="stat-label">总借阅次数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ statistics.currentBorrow || 0 }}</div>
              <div class="stat-label">当前借阅</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ statistics.overdue || 0 }}</div>
              <div class="stat-label">逾期次数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ statistics.onTime || 0 }}</div>
              <div class="stat-label">准时归还</div>
            </div>
          </div>
        </el-card>

        <!-- 借阅历史表格 -->
        <el-card class="history-table-card">
          <template #header>
            <div class="card-header">
              <span>借阅记录</span>
              <el-radio-group v-model="historyFilter" size="small">
                <el-radio-button label="all">全部</el-radio-button>
                <el-radio-button label="current">当前借阅</el-radio-button>
                <el-radio-button label="returned">已归还</el-radio-button>
                <el-radio-button label="overdue">已逾期</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          
          <el-table :data="filteredHistoryData" style="width: 100%" stripe>
            <el-table-column prop="book_name" label="图书名称" min-width="200" show-overflow-tooltip />
            <el-table-column prop="borrow_date" label="借阅日期" width="180" />
            <el-table-column prop="should_return_date" label="应还日期" width="180" />
            <el-table-column prop="return_date" label="实际归还日期" width="180" />
            <el-table-column prop="status" label="状态" width="120">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="historyQuery.currentPage"
              v-model:page-size="historyQuery.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              :total="historyTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleHistorySizeChange"
              @current-change="handleHistoryCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { Avatar, Plus, Camera } from "@element-plus/icons-vue";
import SteamBarcodeReader from "@/components/steambarcodereader.vue";
//引入请求接口
import {getAllCollegeAndMajors, getStudentPagerData,uploadPhoto,addNewStudent,getUserBorrowHistoryData } from "@/api/index.js";
//引入二维码组件
import Qrcode from '@/components/Qrcode.vue'

//查询条件
const searchForm = ref({
  real_name: '', // 学生姓名
  cardno: '', // 借阅卡号
  currentPage: 1,
  pageSize: 10,
});

const tableData = ref([]);
const selectedReader = ref([]);

// 添加预览弹窗控制变量
const cardPreviewVisible = ref(false);

const handleGenerateQR = (reader) => {
  // 确保有card_available字段
  selectedReader.value = {
    ...reader,
    card_available: reader.card_available || `${reader.yearofadmission}.09 - ${Number(reader.yearofadmission) + 4}.07`
  };
  cardPreviewVisible.value = true;
  // 这里可以加上生成二维码的逻辑,使用reader.cardno生成二维码
  // 示例: generateQRCode(reader.cardno)
};

const handlePrint = () => {
  // 打印借阅证逻辑
  console.log("打印借阅证");
};

const dialogVisible = ref(false);
const readerFormRef = ref(null);

const readerForm = ref({
  student_img: "", // 学生照片
  studentno: "",
  username: "", // 账号
  real_name: "", // 真实姓名
  college: "",
  classes: "",
  major: "",
  Yearofadmission: "",
  cardno: "",
  borrow_status: "正常",
  card_available: "",
  collegeAndMajor: [], // 新增院系和专业的级联数组
  photoUrl: '', // 照片预览URL
  photoFile: null, // 照片文件对象
  college_id: '', // 新增 college_id 字段
});

const rules = {
  studentno: [
    { required: true, message: "请输入学号", trigger: "blur" },
    { min: 8, max: 12, message: "学号长度在8到12个字符之间", trigger: "blur" },
    { pattern: /^\d+$/, message: "学号只能包含数字", trigger: "blur" }
  ],
  username: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 4, max: 20, message: "账号长度在4到20个字符之间", trigger: "blur" },
    { pattern: /^[a-zA-Z0-9_]+$/, message: "账号只能包含字母、数字和下划线", trigger: "blur" }
  ],
  real_name: [
    { required: true, message: "请输入真实姓名", trigger: "blur" },
    { min: 2, max: 20, message: "姓名长度在2到20个字符之间", trigger: "blur" },
    { pattern: /^[\u4e00-\u9fa5]{2,20}$/, message: "姓名只能输入中文", trigger: "blur" }
  ],
  collegeAndMajor: [
    {
      required: true,
      message: "请选择学院和专业方向",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (!value || value.length !== 2) {
          callback(new Error("请选择学院和专业方向"));
        } else {
          callback();
        }
      },
    },
  ],
  class: [{ required: true, message: "请输入班级", trigger: "blur" }],
  enrollmentYear: [
    { required: true, message: "请选择入学年份", trigger: "change" },
  ],
};

// 学院和专业数据
const collegeData = ref([]);

// 修改计算属性 collegeOptions
const collegeOptions = computed(() => {
  // 按学院名称分组
  const groupedData = collegeData.value.reduce((acc, curr) => {
    if (!acc[curr.college_name]) {
      acc[curr.college_name] = {
        college_name: curr.college_name,
        majors: []
      };
    }
    acc[curr.college_name].majors.push({
      professional: curr.professional,
      college_id: curr.college_id
    });
    return acc;
  }, {});

  // 转换为级联选择器需要的格式
  return Object.values(groupedData).map(college => ({
    value: college.college_name,
    label: college.college_name,
    children: college.majors.map(major => ({
      value: major.college_id, // 使用 college_id 作为值
      label: major.professional,
    }))
  }));
});

// 页面加载后初始化的地方
onMounted(() => {
  // 请求后端获取学院和专业数据
  getCollegeWithMajorsData();
  // 请求后端获取读者数据
  getUserPagerData(searchForm.value);
});

//请求后端获取学院和专业数据
const getCollegeWithMajorsData = async () => {
  try {
    const res = await getAllCollegeAndMajors();
    if (res && res.code === 200) {
      collegeData.value = res.data;
    } else {
      ElMessage.error("获取院系和专业数据失败");
    }
  } catch (error) {
    console.error("请求失败:", error);
    ElMessage.error("获取院系和专业数据失败");
  }
};
// 调用函数获取数据

const handleAddReader = async () => {
  if (!readerFormRef.value) return;
  await readerFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 构建提交的数据对象
        const submitData = {
          student_img: readerForm.value.student_img,
          studentno: readerForm.value.studentno,
          username: readerForm.value.username,
          real_name: readerForm.value.real_name,
          college_id: readerForm.value.college_id,
          college: readerForm.value.college,
          classes: readerForm.value.class,
          professional: readerForm.value.major,
          yearofadmission: readerForm.value.Yearofadmission
        };

        console.log(submitData);

        const res = await addNewStudent(submitData);
        
        if (res.code === 200) {
          ElMessage.success('添加学生成功');
          dialogVisible.value = false;
          // 重置表单
          readerFormRef.value.resetFields();
          // 重置图片相关字段
          readerForm.value.student_img = '';
          readerForm.value.photoFile = null;
          readerForm.value.photoUrl = '';
          // 重新获取学生列表
          getUserPagerData(searchForm.value);
        } else {
          ElMessage.error(res.msg || '添加学生失败');
        }
      } catch (error) {
        console.error('添加学生失败:', error);
        ElMessage.error(error.response?.data?.message || '添加学生失败');
      }
    }
  });
};

// 添加图片上传前的验证
const beforePhotoUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('只能上传 JPG 或 PNG 格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理图片上传
const handlePhotoUpload = async (params) => {
  const file = params.file
  try {
    const formData = new FormData()
    formData.append('file', file) // 确保与后端接收的字段名一致
    
    const res = await uploadPhoto(formData)
    if (res.code === 200) {
      console.log(res)
      readerForm.value.photoFile = file
      readerForm.value.student_img = res.data; // 拼接完整的图片URL
      ElMessage.success('照片上传成功')
    } else {
      ElMessage.error(res.msg || '照片上传失败')
    }
  } catch (error) {
    console.error('照片上传失败:', error)
    ElMessage.error(error.response?.data?.message || '照片上传失败')
  }
}

// 修改搜索按钮的点击事件
const handleSearch = () => {
  searchForm.value.currentPage = 1; // 重置为第一页
  getUserPagerData(searchForm.value);
};

// 重置搜索
const resetSearch = () => {
  searchForm.value.real_name = ''; // 修改 username 为 real_name
  searchForm.value.cardno = '';
  searchForm.value.currentPage = 1; // 重置页码
  getUserPagerData(searchForm.value);
};

// 修改添加读者按钮的点击事件
const showAddDialog = () => {
  dialogVisible.value = true;
};

// 分页相关数据
const pageTotal = ref(0); // 总页数
const total = ref(0); // 总条数

//自己写分页加载
const pagerTableData = ref([]);

// 请求后端分页数据
const getUserPagerData = async (params) => {
  try {
    const queryParams = {
      ...params,
      real_name: params.real_name.trim(),
      cardno: params.cardno.trim()
    };
    
    const res = await getStudentPagerData(queryParams);
    if (res && res.code === 200) {
      pagerTableData.value = res.data.data;
      pageTotal.value = res.data.pageTotal;
      total.value = res.data.total; // 更新总条数
    } else {
      ElMessage.error("获取学生数据失败");
    }
  } catch (error) {
    console.error("请求失败:", error);
    ElMessage.error("获取学生数据失败");
  }
};
// 分页处理方法
const handleSizeChange = (val) => {
  searchForm.value.pageSize = val;
  searchForm.value.currentPage = 1; // 重置为第一页
  getUserPagerData(searchForm.value); // 重新获取数据
};

const handleCurrentChange = (val) => {
  searchForm.value.currentPage = val;
  getUserPagerData(searchForm.value); // 重新获取数据
};

// 处理级联选择器改变事件
const handleCollegeChange = (value) => {
  if (value && value.length === 2) {
    const college_name = value[0];
    const college_id = value[1]; // 现在这是 college_id
    
    // 查找对应的专业信息
    const majorInfo = collegeData.value.find(item => item.college_id === college_id);
    
    if (majorInfo) {
      readerForm.value.college_id = college_id;
      readerForm.value.college = college_name;
      readerForm.value.major = majorInfo.professional;
    }
  } else {
    readerForm.value.college_id = '';
    readerForm.value.college = '';
    readerForm.value.major = '';
  }
};

// 扫码相关
const scanVisible = ref(false);

const openScan = () => {
  scanVisible.value = true;
};

const handleScanResult = async (result) => {
  if (!result) {
    ElMessage.error('扫描失败，请重试');
    return;
  }

  try {
    // 获取扫描文本
    const scannedText = result.text || result;
    
    // 更新借阅卡号输入框
    searchForm.value.cardno = scannedText;

    // 关闭扫描窗口
    scanVisible.value = false;
    
    // 播放提示音
    const audio = new Audio('/assets/beep.mp3');
    audio.play().catch(err => console.warn('播放提示音失败:', err));

    ElMessage.success('扫描成功');
    
    // 自动触发搜索
    handleSearch();
  } catch (error) {
    console.error('扫描处理错误:', error);
    ElMessage.error('扫描处理出错，请重试');
  }
};

// 抽屉相关
const drawerVisible = ref(false);
const currentReader = ref({});
const historyFilter = ref('all');
const historyTotal = ref(0);

// 借阅历史查询参数
const historyQuery = ref({
  currentPage: 1,
  pageSize: 10
});

// 统计数据
const statistics = ref({
  totalBorrow: 0,
  currentBorrow: 0,
  overdue: 0,
  onTime: 0
});

// 借阅历史数据
const historyData = ref([]);

// 根据筛选条件过滤数据
const filteredHistoryData = computed(() => {
  if (historyFilter.value === 'all') return historyData.value;
  return historyData.value.filter(item => {
    switch (historyFilter.value) {
      case 'current':
        return !item.return_date;
      case 'returned':
        return item.return_date && item.status !== 'overdue';
      case 'overdue':
        return item.status === 'overdue';
      default:
        return true;
    }
  });
});

// 显示借阅历史
const showBorrowHistory = async (reader) => {
  currentReader.value = reader;
  drawerVisible.value = true;
  // 重置筛选和分页
  historyFilter.value = 'all';
  historyQuery.value.currentPage = 1;
  await loadBorrowHistory(reader.user_id);
};

// 加载借阅历史数据
const loadBorrowHistory = async (userId) => {
  try {
    const params = {
      currentPage: historyQuery.value.currentPage,
      pageSize: historyQuery.value.pageSize,
      user_id: userId,
      borrow_status: '' // 默认空字符串获取所有状态
    }
    
    const res = await getUserBorrowHistoryData(params);
    if (res.code === 200) {
      // 格式化数据
      historyData.value = res.data.userHistoryPagerData.data.map(item => ({
        book_name: item.title,
        borrow_date: item.borrow_time,
        should_return_date: item.due_time,
        return_date: item.return_time,
        status: !item.return_time ? 'borrowing' : 
                new Date(item.return_time) > new Date(item.due_time) ? 'overdue' : 'returned'
      }));
      
      // 更新统计数据
      const stats = res.data.userHistoryStatus;
      statistics.value = {
        totalBorrow: stats.total_borrows,
        currentBorrow: stats.current_borrows, 
        overdue: stats.overdue_times,
        onTime: stats.ontime_returns
      };

      // 更新分页数据
      historyTotal.value = res.data.userHistoryPagerData.total;
    } else {
      ElMessage.error(res.msg || '获取借阅历史失败');
    }
  } catch (error) {
    console.error('获取借阅历史失败:', error);
    ElMessage.error('获取借阅历史失败');
  }
};

// 处理分页大小变化
const handleHistorySizeChange = (val) => {
  historyQuery.value.pageSize = val;
  historyQuery.value.currentPage = 1; // 重置到第一页
  loadBorrowHistory(currentReader.value.user_id);
};

// 处理页码变化 
const handleHistoryCurrentChange = (val) => {
  historyQuery.value.currentPage = val;
  loadBorrowHistory(currentReader.value.user_id);
};

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'borrowing':
      return 'warning';
    case 'returned':
      return 'success';
    case 'overdue':
      return 'danger';
    default:
      return 'info';
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'borrowing':
      return '借阅中';
    case 'returned':
      return '已归还';
    case 'overdue':
      return '已逾期';
    default:
      return '未知';
  }
};
</script>

<style scoped>
.readers-container {
  padding: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.table-card {
  margin-top: 20px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.qr-card {
  height: 100%;
}

.reader-card {
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.card-info {
  margin-bottom: 20px;
}

.qr-code-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  background: #f5f7fa;
  border-radius: 4px;
}

.qr-placeholder {
  color: #909399;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.library-card {
  width: 100%;
  background: #ffffff;
  border: 2px solid #ff4d4f; /* 改为红色边框 */
  border-radius: 12px;
  box-shadow: 0 6px 20px rgba(255, 77, 79, 0.2),
    /* 主阴影 */ 0 2px 8px rgba(255, 77, 79, 0.1); /* 次阴影，增加层次感 */
  padding: 24px;
  box-sizing: border-box;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 2px solid #1890ff;
  padding-bottom: 15px;
  margin-bottom: 0;
}

.card-header h2 {
  color: #1890ff;
  margin: 0;
}

.card-no {
  color: #666;
  font-size: 14px;
}

.card-body {
  display: flex;
  gap: 30px;
  padding: 20px 0;
  align-items: stretch;
  min-height: 240px;
}

/* 移除card-section的背景和边框样式 */
.card-section {
  padding: 15px;
}

/* 左侧照片区域 */
.photo-section {
  width: 160px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.photo-placeholder {
  width: 150px;
  height: 200px;
  background: #fff; /* 改为白色背景 */
  border: 1px dashed #d9d9d9;
  display: flex;
  align-items: center;
  justify-content: center;
}

.student-photo {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 中间信息区域 */
.info-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center; /* 修改为居中对齐 */
  gap: 15px; /* 使用gap替代margin-bottom */
  padding: 20px;
}

.info-row {
  display: flex;
  align-items: center;
}

/* 右侧二维码区域 */
.qr-section {
  width: 160px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.qr-placeholder {
  width: 120px;
  height: 120px;
  background: #fff; /* 改为白色背景 */
  border: 1px dashed #d9d9d9;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}

.qr-tip {
  color: #666;
  font-size: 12px;
  margin-top: 8px;
}

.card-footer {
  margin-top: 0;
  padding-top: 15px;
  border-top: 1px solid #eee;
  text-align: right;
  color: #666;
  font-size: 12px;
}

.card-preview-dialog :deep(.el-dialog__body) {
  padding: 24px;
  max-height: calc(90vh - 120px);
  overflow-y: auto;
}

/* 添加表格单元格溢出处理 */
:deep(.el-table .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.reader-form :deep(.el-form-item) {
  margin-bottom: 22px;
}

.reader-form :deep(.el-divider) {
  margin: 16px 0;
}

.reader-form :deep(.el-divider__text) {
  font-size: 14px;
  color: #606266;
}

.reader-form :deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-start; /* 修改为左对齐 */
  padding-left: 16px; /* 添加左侧内边距，使其与表格对齐 */
}

.upload-container {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.avatar-uploader {
  width: 180px;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.avatar-placeholder {
  width: 180px;
  height: 240px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.avatar {
  width: 180px;
  height: 240px;
  object-fit: cover;
}

.upload-tip {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  line-height: 1.5;
}

.upload-tip p {
  margin: 4px 0;
}

:deep(.el-input-group__append) {
  padding: 0;
}

:deep(.el-input-group__append .el-button) {
  padding: 8px 12px;
  margin: 0;
  height: 100%;
  border: none;
}

:deep(.el-input-group__append .el-button:hover) {
  background-color: var(--el-button-hover-bg-color);
  color: var(--el-button-hover-text-color);
}

/* 借阅历史抽屉样式 */
.borrow-history-container {
  padding: 20px;
  background-image: linear-gradient(126deg, #f4f7ff, #eeedfb, #c4e9fc);
  min-height: 100%;
}

.statistics-card {
  margin-bottom: 20px;
}

.statistics-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background-color: var(--el-bg-color-overlay);
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-lighter);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-color-primary);
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.history-table-card {
  margin-top: 20px;
}

.history-table-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.history-table-card :deep(.el-card__header) {
  padding: 15px 20px;
}
</style>
